<template>
  <div class="container" style="height: 100%">
    <div class="flex_cm" style="height: 100%">
      <search
        :data="header_list"
        @changeIsShow="
          (e) => {
            header_list[e].isShow = !header_list[e].isShow
            header_list[e].value =
              header_list[e].type == 'input_number' ? ['', ''] : ''
          }
        "
        @search="search_key"
        @reset="
          header_list.forEach((item) => {
            item.value = ''
          }),
            search_key()
        "
      ></search>
      <div class="p_0_10 bg_fff flex1">
        <div class="flex_js p_10_0">
          <div class="c_666 fw">账号管理</div>
          <div class="flex">
            <el-button
              type="primary"
              @click="show_box = true"
              v-if="has_role_list[3].has_role"
              >新增账号</el-button
            >
            <setTable
              :data="header_list"
              :height_size="height_size"
              @changeShowTable="
                (e) => {
                  header_list[e].showTable = !header_list[e].showTable
                }
              "
              @resetTableSet="
                () => {
                  header_list.forEach((item) => {
                    item.showTable = true
                  })
                }
              "
              @changeHeightSize="
                (e) => {
                  height_size = e
                }
              "
            ></setTable>
          </div>
        </div>
        <myTable
          :data="list"
          :maxHeight="max_height"
          :height_size="height_size"
          :loading="loading"
          :header_list="header_list"
          @edit_list="edit_list"
        ></myTable>

        <el-pagination
          class="m_10_0 pagination"
          v-model:currentPage="form_data.current"
          v-model:page-size="form_data.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="
            (e) => {
              form_data.pageSize = e
              get_list()
            }
          "
          @current-change="
            (e) => {
              form_data.current = e
              get_list()
            }
          "
        />
      </div>
    </div>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      @close="resetForm(adduserform)"
      size="40%"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <template #title>
        <h4 v-if="add_form_data.id == ''">新增账号</h4>
        <h4 v-else>修改账号</h4>
      </template>
      <template #default>
        <el-form
          ref="adduserform"
          :rules="rules"
          :model="add_form_data"
          label-width="100px"
        >
          <el-form-item label="头像">
            <upload
              :imageUrl="add_form_data.headPic"
              :limit="1"
              :accept="'image/jpeg,image/jpg,image/png'"
            ></upload>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="add_form_data.username"
              placeholder="请输入用户名"
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="密码"
            prop="password"
            v-if="add_form_data.id == ''"
          >
            <el-input
              v-model="add_form_data.password"
              placeholder="请输入密码"
              show-word-limit
              maxlength="6"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickname">
            <el-input
              v-model="add_form_data.nickname"
              placeholder="请输入用户昵称"
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="userRoleDealVOList">
            <el-select
              v-model="add_form_data.userRoleDealVOList"
              multiple
              placeholder="请选择角色"
            >
              <el-option
                v-for="item in role_list"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input
              v-model="add_form_data.email"
              placeholder="请输入邮箱"
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="微信">
            <el-input
              v-model="add_form_data.wechat"
              placeholder="请输入微信"
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input
              v-model="add_form_data.phone"
              placeholder="请输入手机号"
              show-word-limit
              maxlength="11"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio
              v-model="add_form_data.status"
              :label="1"
              :disabled="!has_role_list[0].has_role"
              >启用</el-radio
            >
            <el-radio
              v-model="add_form_data.status"
              :label="0"
              :disabled="!has_role_list[0].has_role"
              >停用</el-radio
            >
          </el-form-item>
          <el-form-item label="用户描述">
            <el-input
              type="textarea"
              rows="4"
              v-model="add_form_data.remark"
              placeholder="请输入用户描述"
              show-word-limit
              maxlength="300"
            ></el-input>
          </el-form-item>
          <div class="tr m_top10">
            <el-button @click="resetForm(adduserform)">取消</el-button>
            <el-button
              type="primary"
              @click="submit(adduserform)"
              :loading="btn_loading"
              >保存</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
    <el-drawer
      v-model="edit_pwd_box"
      direction="rtl"
      @close="resetForm(editPwdform)"
      size="40%"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <template #title>
        <h4>修改密码</h4>
      </template>
      <template #default>
        <el-form
          ref="editPwdform"
          :rules="rules"
          :model="pwd_form_data"
          label-width="100px"
        >
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="pwd_form_data.newPassword"></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="reNewPassword">
            <el-input
              type="password"
              v-model="pwd_form_data.reNewPassword"
            ></el-input>
          </el-form-item>
          <div class="tr m_top10">
            <el-button @click="resetForm(editPwdform)">取消</el-button>
            <el-button
              type="primary"
              :loading="btn_loading"
              @click="submit_edit_pwd(editPwdform)"
              >确定</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { check_role, handle_search_key } from '@/utils/utils'
import search from '@/view/components/search.vue'
import myTable from '@/view/components/myTable.vue'
import { onMounted, ref, reactive, onUnmounted, nextTick } from 'vue'
import { FormInstance, ElMessage, FormRules, ElMessageBox } from 'element-plus'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import setTable from '@/view/components/setTable.vue'
import upload from '@/view/components/upload.vue'
const adduserform = ref<FormInstance>()
const editPwdform = ref<FormInstance>()
const rules = reactive<FormRules>({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  nickname: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
  userRoleDealVOList: [
    { required: true, type: 'array', message: '请选择角色', trigger: 'change' },
  ],
  newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  reNewPassword: [{ required: true, message: '请确认新密码', trigger: 'blur' }],
})
const pwd_form_data = ref({
  id: '',
  newPassword: '',
  reNewPassword: '',
})
const edit_pwd_box = ref(false)
const edit_pwd = (e) => {
  console.log(e)
  pwd_form_data.value.id = e.row.id
  edit_pwd_box.value = true
}
const has_role_list = ref([
  { path: 'user/status', has_role: false },
  { path: 'user/put', has_role: false },
  { path: 'user/delete', has_role: false },
  { path: 'user/post', has_role: false },
  { path: 'user/updatePwd', has_role: false },
])
const max_height = ref()
nextTick(() => {
  max_height.value = window.innerHeight - 320 // 带分页的 table 高度
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item.path)
  })
})
const loading = ref(false)
const list = ref([])
const role_list = ref([])
const header_list = ref<any>([
  {
    label: '用户名',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
    prop: 'username',
  },
  {
    label: '用户昵称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
    prop: 'nickname',
  },
  {
    label: '邮箱',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
    prop: 'email',
  },
  {
    label: '角色',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
    prop: 'roleName',
  },
  {
    label: '状态',
    value: '',
    showTable: true,
    type: 'select',
    isShow: false,
    options: [
      { label: '已启用', value: '1' },
      { label: '已停用', value: '0' },
    ],
    prop: 'status',
  },
  {
    label: '微信',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
    prop: 'wechat',
  },
  {
    label: '手机号',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
    prop: 'phone',
  },
  {
    label: '用户描述',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
    prop: 'description',
    show_overflow_tooltip: true,
  },
])
const form_data = ref({
  current: 1,
  nickname: '',
  username: '',
  pageSize: 10,
  roleName: '',
  email: '',
  wechat: '',
  phone: '',
  remark: '',
  status: '',
})
const add_form_data = ref({
  id: '',
  nickname: '',
  username: '',
  password: '',
  userRoleDealVOList: [],
  email: '',
  wechat: '',
  phone: '',
  status: 1,
  remark: '',
  headPic: [],
})

const total = ref()
const height_size = ref(1) // 行高
const show_box = ref(false)
onMounted(() => {
  EventBus.on('refresh', () => {
    // 刷新
    get_list()
    ElMessage.success('刷新成功！')
  })
  get_list()
  get_role_list()
})
onUnmounted(() => {
  EventBus.off('refresh')
})
const edit_list = (e) => {
  console.log(e)
  if (e.type == 1) {
    pwd_form_data.value.id = e.item.id
    edit_pwd_box.value = true
  } else if (e.type == 2 || e.type == 3) {
    ElMessageBox.confirm(
      e.item.status ? '确定停用该记录？' : '确定启用该记录？',
      '',
      {
        closeOnClickModal: false,
        type: 'warning',
      }
    )
      .then(() => {
        axios
          .request({
            url:
              e.item.status == 1
                ? serviceApi.user_disable + '/' + e.item.id
                : serviceApi.user_enable + '/' + e.item.id,
            method: 'put',
          })
          .then(() => {
            ElMessage.success('操作成功！')
            setTimeout(() => {
              get_list()
            }, 1000)
          })
          .catch((error) => {
            ElMessage.error(error)
          })
      })
      .catch(() => {})
  } else if (e.type == 4) {
    add_form_data.value = Object.assign(add_form_data.value, e.item)
    add_form_data.value.status = e.item.status ? 1 : 0
    role_list.value.forEach((item) => {
      if (e.item.roleName.split(' ').includes(item.name)) {
        add_form_data.value.userRoleDealVOList.push(item.id)
      }
    })
    add_form_data.value.headPic = e.item.headPic
      ? e.item.headPic.split(',')
      : []
    show_box.value = true
  } else {
    ElMessageBox.confirm('确定删除该记录？', '', {
      closeOnClickModal: false,
      type: 'warning',
    })
      .then(() => {
        axios
          .request({
            url: serviceApi.user_crud + '/' + e.item.id,
            method: 'delete',
          })
          .then(() => {
            ElMessage.success('删除成功！')
            setTimeout(() => {
              get_list()
            }, 1000)
          })
          .catch((error) => {
            ElMessage.error(error)
          })
      })
      .catch(() => {})
  }
}
const get_role_list = () => {
  axios
    .request({
      url: serviceApi.role_list,
      method: 'post',
      data: { current: 1, pageSize: 100, platformType: '1' },
    })
    .then((res) => {
      console.log(res)
      header_list.value[3].options = res.data.content
      role_list.value = res.data.content
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}

const get_list = () => {
  loading.value = true
  axios
    .request({
      url: serviceApi.user_list,
      method: 'post',
      data: handle_search_key(form_data.value),
    })
    .then((res) => {
      console.log(res)
      res.data.content.forEach((i) => {
        i.btn_list = i.isAdmin
          ? []
          : [
              {
                label: '修改密码',
                icon: 'editPwd',
                has_role: has_role_list.value[3].has_role,
                btn_show: true,
              },
              {
                label: '禁用',
                icon: 'table_status_enable',
                has_role: has_role_list.value[0].has_role,
                btn_show: i.status,
              },
              {
                label: '启用',
                icon: 'table_status_disable',
                has_role: has_role_list.value[0].has_role,
                btn_show: !i.status,
              },
              {
                label: '编辑',
                icon: 'table_edit',
                has_role: has_role_list.value[1].has_role,
                btn_show: true,
              },
              {
                label: '删除',
                icon: 'table_delete',
                has_role: has_role_list.value[2].has_role,
                btn_show: true,
              },
            ]
      })
      list.value = res.data.content
      total.value = parseInt(res.data.totalElements)
      loading.value = false
    })
    .catch((error) => {
      ElMessage.error(error)
      loading.value = false
    })
}
const btn_loading = ref(false)
const submit_edit_pwd = async (formEl: FormInstance | undefined) => {
  if (pwd_form_data.value.newPassword != pwd_form_data.value.reNewPassword) {
    ElMessage.error('两次输入的密码不一致，请仔细核对')
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return
      btn_loading.value = true
      axios
        .request({
          url: serviceApi.editPwd,
          method: 'put',
          data: pwd_form_data.value,
        })
        .then((res) => {
          console.log(res)
          ElMessage.success('操作成功！')
          resetForm(formEl)
          btn_loading.value = false
        })
        .catch((err) => {
          ElMessage.error(err)
          btn_loading.value = false
        })
    }
  })
}
const submit = async (formEl: FormInstance | undefined) => {
  let submit_data = JSON.parse(JSON.stringify(add_form_data.value))
  submit_data.headPic = submit_data.headPic.toString()
  for (let i in submit_data.userRoleDealVOList) {
    var a = {
      roleId: submit_data.userRoleDealVOList[i],
    }
    submit_data.userRoleDealVOList.splice(i, 1, a)
  }
  console.log(submit_data)
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return
      btn_loading.value = true
      if (submit_data.id != '') {
        delete submit_data.password
      }
      axios
        .request({
          url:
            submit_data.id == ''
              ? serviceApi.user_crud
              : serviceApi.user_crud + '/' + submit_data.id,
          method: submit_data.id == '' ? 'post' : 'put',
          data: submit_data,
        })
        .then((res) => {
          console.log(res)
          ElMessage.success('操作成功！')
          setTimeout(() => {
            get_list()
            show_box.value = false
            btn_loading.value = false
          }, 1000)
        })
        .catch((error) => {
          ElMessage.error(error)
          btn_loading.value = true
        })
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  show_box.value = false
  add_form_data.value = {
    id: '',
    nickname: '',
    username: '',
    password: '',
    userRoleDealVOList: [],
    email: '',
    wechat: '',
    phone: '',
    status: 1,
    remark: '',
    headPic: [],
  }
  edit_pwd_box.value = false
  pwd_form_data.value = {
    id: '',
    newPassword: '',
    reNewPassword: '',
  }
}
const search_key = () => {
  form_data.value = {
    current: 1,
    pageSize: 10,
    username: header_list.value[0].value,
    nickname: header_list.value[1].value,
    email: header_list.value[2].value,
    roleName: header_list.value[3].value,
    status:
      header_list.value[4].value == ''
        ? header_list.value[4].value
        : (parseInt(header_list.value[4].value) as any),
    wechat: header_list.value[5].value,
    phone: header_list.value[6].value,
    remark: header_list.value[7].value,
  }
  get_list()
}
</script>

<style lang="scss" scoped>
:deep(.el-switch__core) {
  width: 70px !important;
}
</style>
